package com.wwz.swordfingeroffer;

import org.junit.Test;

/**
 * 第k大数
 */
public class swordFinger76 {

    @Test
    public void test() {
        System.out.println(findKthLargest(new int[]{3, 2, 1, 5, 6, 4}, 2));
    }

    public int findKthLargest(int[] nums, int k) {
        return getIndex(nums, 0, nums.length - 1, nums.length - k);
    }

    public int getIndex(int[] nums, int left, int right, int target) {
        int index = quickSort(nums, left, right);
        if (target == index) {
            return nums[target];
        } else {
            return index > target ? getIndex(nums, left, index - 1, target) : getIndex(nums, index + 1, right, target);
        }

    }

    public int quickSort(int[] nums, int left, int right) {
        int povit = nums[left];
        while (left < right) {
            while (left < right && nums[right] >= povit) {
                right--;
            }
            nums[left] = nums[right];
            while (left < right && nums[left] <= povit) {
                left++;
            }
            nums[right] = nums[left];
        }
        nums[left] = povit;
        return left;
    }
}
